<!-- Collapse.svelte-->
<script lang="ts">
	import { setContext } from 'svelte';
	const {
		children,
		modelValue = $bindable<string[]>([]),
		accordion = false,
		onUpdate
	} = $props<{
		children: any;
		modelValue: string | string[];
		accordion?: boolean;
		onUpdate?: (next: string[]) => void; // ← 回调式
	}>();

	let activeNames = $state<string[]>(Array.isArray(modelValue) ? modelValue : [modelValue]);

	$effect(() => {
		activeNames = Array.isArray(modelValue) ? modelValue : [modelValue];
	});

	function handleItemClick(name: string) {
		const next = accordion
			? activeNames.includes(name)
				? []
				: [name]
			: activeNames.includes(name)
				? activeNames.filter((n) => n !== name)
				: [...activeNames, name];

		activeNames = next;
		onUpdate?.(next);
	}

	// 向子组件提供上下文
	setContext('collapse', {
		activeNames: () => activeNames, // 每次调用都能获取最新值
		handleItemClick
	});
</script>

<div class="s-collapse">
	{@render children?.()}
</div>

<style>
	.s-collapse {
		border: var(--border);
		border-radius: 4px;
	}
</style>
